import 'dart:convert';

import 'filter_item_data.dart';

class FilterUtils {
  static FilterItemData? jsonToFilterData(String? json) {
    if (json != null) {
      var config = jsonDecode(json);
      return FilterItemData.fromJson(config);
    } else {
      return null;
    }
  }

  static List<FilterItemData>? jsonToFilterList(String? json) {
    if (json != null) {
      var config = jsonDecode(json);
      if (List == config.runtimeType) {
        return (config as List).map((e) => FilterItemData.fromJson(e)).toList();
      } else {
        return null;
      }
    } else {
      return null;
    }
  }

  static List<FilterItemData> addFilterItemToList(
      List<FilterItemData> filterItemList,
      String key,
      List<FilterItemData> list) {
    for (FilterItemData itemData in filterItemList) {
      if (itemData.children != null) {
        if (itemData.code == key) {
          itemData.children!.addAll(list);
        } else {
          addFilterItemToList(itemData.children!, key, list);
        }
      }
    }
    return filterItemList;
  }

  static FilterItemData addFilterItem(
      FilterItemData filterItemData, String key, List<FilterItemData> list) {
    if (filterItemData.children != null) {
      if (filterItemData.code == key) {
        filterItemData.children!.addAll(list);
      } else {
        addFilterItemToList(filterItemData.children!, key, list);
      }
    }
    return filterItemData;
  }
}
